window.addEventListener("message", async function (event) {
    let message = {"from": "web", "action": event.data.action};
    if (event.data.from === "extenstion" && event.data.action == "telemetry") {
        message.data = window.bmak.get_telemetry();
        window.postMessage(message, "*");
    }
    if (event.data.from === "extenstion" && event.data.action == "localStorage_get") {
        let keyArr = event.data.data;
        let len = window.localStorage.length;
        let arr = new Array();
        for (let i = 0; i < len; i++) {
            let getKey = window.localStorage.key(i);
            let getVal = window.localStorage.getItem(getKey);
            arr[i] = {'key': getKey, 'val': getVal};
        }
        if (!!keyArr && keyArr.length > 0) {
            arr = arr.filter(item => keyArr.indexOf(item.key) != -1);
        }
        message.data = arr;
        window.postMessage(message, "*");
    }
    if (event.data.from === "extenstion" && event.data.action == "localStorage_set") {
        let data = event.data.data;
        for (let obj of data) {
            window.localStorage.setItem(obj.key, obj.val);
        }
        window.postMessage(message, "*");
    }
    if (event.data.from === "extenstion" && event.data.action == "localStorage_del") {
        let keyArr = event.data.data;
        if (!!keyArr && keyArr.length > 0) {
            for (let key of keyArr) {
                window.localStorage.removeItem(key);
            }
        } else {
            window.localStorage.clear();
        }
        window.postMessage(message, "*");
    }
});